package file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;


public class VideoProcess {

	public static void main(String[] args) throws Exception{
//		String content = "so good";  
//        String password = "12345678";  
//        // 加密  
//        System.out.println("加密前：" + content);  
//        byte[] encryptResult = encrypt(content, password);
//        
//        // 解密  
//        byte[] decryptResult = decrypt(encryptResult, password);  
//        System.out.println("解密后：" + new String(decryptResult));
        
		
		//File oriFile = new File("D:/clear.avi");
		//KeyGenerator kgen = KeyGenerator.getInstance("AES");
        //byte key[] = {0x00,0x32,0x22,0x11,0x00,0x00,0x00,0x00,0x00,0x23,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
//        SecretKey skey = kgen.generateKey();
//        
//       String stringKey = kgen.toString();
//        
//        byte[] key = skey.getEncoded();
//        
//        stringKey = new String(key,"UTF-32");
//        System.out.println("keyString is " + stringKey);
//        
//        String a = Arrays.toString(key);
//        
//        System.out.println("key:"+ Arrays.toString(key));
//        
//        byte[] raw =stringKey.getBytes("UTF-32");
//        
//        System.out.println("raw:"+ Arrays.toString(raw));
//        
//        SecretKey skey2 =  new SecretKeySpec(raw, "AES");
//        
//        
//        
//		File outFile = encryptVideo(oriFile,skey);
//		
//		decrptVideo(outFile,skey);
		//InputStream stream = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("D:\\clear.avi"); 
		//StreamedContent enhanceVideo = new DefaultStreamedContent(stream, "avi", "dd");
		
	}
	public static byte[] encrypt(String content, String password) {  
        byte[] result;  
        try {  
            //指定一个算法生成KeyGenerator对象，这里使用 AES 算法  
            KeyGenerator kgen = KeyGenerator.getInstance("AES");  
            //SecureRandom,此类提供加密的强随机数生成器  
            //用指定参数集和用户提供的随机源初始化此密钥生成器  
            kgen.init(128, new SecureRandom(password.getBytes()));  
            //kgen.generateKey()生成一个密钥  
            SecretKey secretKey = kgen.generateKey();  
            //返回基本编码格式的密钥，如果此密钥不支持编码，则返回 null  
            byte[] enCodeFormat = secretKey.getEncoded();  
            //根据给定的字节数组构造一个密钥  
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");  
            //生成一个实现指定转换的 Cipher 对象  
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器  
            byte[] byteContent = content.getBytes("utf-8");  
            //用密钥初始化此 cipher  
            cipher.init(Cipher.ENCRYPT_MODE, key);  
            //按单部分操作加密或解密数据，或者结束一个多部分操作,数据被加密还是解密取决于此 cipher 的初始化方式   
            result = cipher.doFinal(byteContent);  
            System.out.println("======"+result.toString());  
            return result; // 加密,生成密钥内容  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return null;  
    }  
  
    /** 
     * 解密 
     *  
     * @param content 
     *            待解密内容 
     * @param password 
     *            解密密钥 
     * @return 
     */  
    public static byte[] decrypt(byte[] content, String password) {  
        try {  
            KeyGenerator kgen = KeyGenerator.getInstance("AES");  
            kgen.init(128, new SecureRandom(password.getBytes()));  
            SecretKey secretKey = kgen.generateKey();  
            byte[] enCodeFormat = secretKey.getEncoded();  
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");  
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器  
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化  
            byte[] result = cipher.doFinal(content);  
            return result; // 加密  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
	
	public static void enhanceVideo(String oriPath,String ehancePath) throws Exception{
		
		Runtime rn = Runtime.getRuntime();
		Process p = null;
		String commond = "";
		commond += "cmd /c start D:\\video\\VideoEnhancer.exe ";
		commond += " -i ";
		commond += oriPath;
		commond += " -o ";
		commond += ehancePath;
		commond += " -d 640 480 -vc Huff -fast ";
		
		try {
			p = rn.exec(commond);
			//p = rn.exec("cmd /c start D:\\video\\VideoEnhancer.exe -i D:\\wang.avi -o D:\\176qq.avi -d 640 480 -vc Huff -fast");
		} catch (Exception e) {
			System.out.println("Error exec!");
		}
	}
	
	public static File encryptVideo(File oriFile,SecretKey skey) throws Exception{
		FileInputStream fis = new FileInputStream(oriFile);
		String fileName = oriFile.getName();
		System.out.println(fileName);
		
        File outfile = new File("D:/wang1.avi");
        int read;
        if(!outfile.exists())
            outfile.createNewFile();
        
        FileOutputStream fos = new FileOutputStream(outfile);
        
        
        Cipher encipher = Cipher.getInstance("AES");
        
        encipher.init(Cipher.ENCRYPT_MODE, skey);
        CipherInputStream cis = new CipherInputStream(fis, encipher);
        
        while((read = cis.read())!=-1)
                {
                    fos.write((char)read);
                    fos.flush();
                }   
        fos.close();
        
        return outfile;
	}
	
	public static File encryptVideo(File oriFile,SecretKey skey,File outfile) throws Exception{
		FileInputStream fis = new FileInputStream(oriFile);
		String fileName = oriFile.getName();
		System.out.println(fileName);
		
        int read;
        if(!outfile.exists())
            outfile.createNewFile();
        
        FileOutputStream fos = new FileOutputStream(outfile);
        
        
        Cipher encipher = Cipher.getInstance("AES");
        
        encipher.init(Cipher.ENCRYPT_MODE, skey);
        CipherInputStream cis = new CipherInputStream(fis, encipher);
        
        while((read = cis.read())!=-1)
                {
                    fos.write((char)read);
                    fos.flush();
                }   
        fos.close();
        
        return outfile;
	}
	
	public static void decrptVideo(File encryptFile,SecretKey skey)throws Exception{
        int read;
        File decfile = new File("D:/wang2.avi");
        if(!decfile.exists())
            decfile.createNewFile();
        
        FileInputStream encfis = new FileInputStream(encryptFile);
        FileOutputStream decfos = new FileOutputStream(decfile);
        Cipher decipher = Cipher.getInstance("AES");

        //Lgo

        decipher.init(Cipher.DECRYPT_MODE, skey);
        CipherOutputStream cos = new CipherOutputStream(decfos,decipher);
        
        while((read=encfis.read())!=-1)
        {
            cos.write(read);
            cos.flush();
        }
        cos.close();
	}
	
	public static void decrptVideo(File encryptFile,SecretKey skey,File decfile)throws Exception{
        int read;
        //File decfile = new File("D:/wang2.avi");
        if(!decfile.exists())
        	
            decfile.createNewFile();
        
        FileInputStream encfis = new FileInputStream(encryptFile);
        FileOutputStream decfos = new FileOutputStream(decfile);
        Cipher decipher = Cipher.getInstance("AES");

        //Lgo

        decipher.init(Cipher.DECRYPT_MODE, skey);
        CipherOutputStream cos = new CipherOutputStream(decfos,decipher);
        
        while((read=encfis.read())!=-1)
        {
            cos.write(read);
            cos.flush();
        }
        cos.close();
	}
}
